package com.adrian.controller;

import com.adrian.api.ApiClient;
import com.adrian.pojo.Product;
import com.adrian.pojo.Type;
import com.adrian.result.MessageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Auther: Adrian
 * @Date: 2020/3/22 10:38
 * @Description:
 */
@Controller
@Scope("prototype")
public class ProductTypeController {

    @Autowired
    private ApiClient apiClient;

    @RequestMapping("/type")
    public String typeUI(){
        return "redirect:typeList";
    }

    @RequestMapping("/typeList")
    public String typeList(Model model){
        List<Type> types = apiClient.getTypes();
        model.addAttribute("types",types);
        return "type";
    }

    @ResponseBody
    @RequestMapping("/type_add")
    public MessageResult addType(Type type){
        MessageResult result=null;
        int count = apiClient.addType(type);
        if(count>0){
            result = new MessageResult(200, "新增成功");
        }else{
            result = new MessageResult(500, "新增失败");
        }
        return result;
    }
    @RequestMapping("/type_delete")
    @ResponseBody
    public MessageResult deleteType(int id) {
        int i = apiClient.deleteType(id);
        MessageResult result =new MessageResult();
        if (i>0){
            result.setCode(200);
            result.setMsg("删除成功");
        }else {
            result.setCode(500);
            result.setMsg("更新失败");
        }
        return result;
    }

    @RequestMapping("/type_update")
    @ResponseBody
    public MessageResult uptadeType(Type type){
        int count = apiClient.addType(type);
        MessageResult result =null;
        if(count>0){
            result = new MessageResult(200, "更新成功");
        }else{
            result = new MessageResult(500, "更新失败");
        }
        return result;
    }

    @RequestMapping("/type_toupdate")
    public String getTypeById(int id,Model model){
        Type types = apiClient.getTypeById(id);
        model.addAttribute("type",types);
        return "edittypes";
    }
}
